package eg.backend.manager.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.providers.encoding.PasswordEncoder;

import eg.backend.base.ContextHolder;
import eg.backend.base.UserType;
import eg.backend.domain.User;
import eg.backend.manager.UserManager;
import eg.backend.repository.UserRepository;

public class UserManagerImpl implements UserManager {
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private ContextHolder contextHolder;	
	@Autowired(required = false)
	private PasswordEncoder passwordEncoder;
	
	public User logonUser(String email, String password) {
		User user = userRepository.findByEmail(email);
		if(user != null) {
			if (passwordEncoder != null) {
				password = passwordEncoder.encodePassword(password, null);
			}
			if(user.getPassword().equals(password))
				return user;
		}
		return null;
	}
	
	public User getCurrentUser() {
		//this can be put to MemCache, userId <-> user, so that it needn't query dataStore each time
		//so it is with logon part: email <-> user
		String id = contextHolder.getUserId();
		return userRepository.get(id);
	}
	
	public String getCurrentUserId() {
		return contextHolder.getUserId();
	}

	public String getCurrentUsername() {
		return contextHolder.getUserName();
	}

	public void changePassword(String password) {
		if (passwordEncoder != null) {
			password = passwordEncoder.encodePassword(password, null);
		}
		getCurrentUser().setPassword(password);
	}

	public User createUser(String email, String password) {
		User user = userRepository.findByEmail(email);
		if(user == null) {
			user = new User();
			if (passwordEncoder != null) {
				password = passwordEncoder.encodePassword(password, null);
			}
			user.setEmail(email);
			user.setPassword(password);
			user.setUsername(email);
			user.setType(UserType.NORMAL);
			userRepository.save(user);
			return user;
		}
		return null;
	}

}
